<?php
require 'XMLHttpRequest.php';

class baseAPIClass{
	public static function debug($value){
		echo "<pre>";
		print_r($value);
		echo "</pre>";
	}
}

class HTTPApi{
	protected $options=null;
	
	public function __construct($options){
		$this->options=$options;
	}
	
	private function build_url($options){
		$url.=(($this->options['secure']==true)?"https":"http")."://";
		$url.=$this->options['host'];
		$url.=(empty($this->options["port"])?"":":".$this->options["port"]);
		$url.=$options['url'];
	
		foreach ( $options['params'] as $name => $value ) {
			$url.="?";
			$concat="";
			if(is_array($value)){
				$last_item = end($value);
				foreach ( $value as $value1 ) {
					$concat.= trim(urlencode($value1));
			
					if($last_item!=$value1){
						$concat.= ",";
					}
				}
			}else{
				$concat=trim(urlencode($value));
			}
			$url.= trim(urlencode($name)).'='.$concat.'&';
		}
		return $url;
	}

	private function do_request($verb,$options){
		if(empty($options['params'])){
			$options['params']=array();
		}
		$url=$this->build_url($options);

		$ajax = new XMLHttpRequest();
		$ajax->open($verb,$url,false,$this->options['username'],$this->options['password']);
		
		$response=NULL;
		
		//	Add the headers
		foreach ( $options['headers'] as $name => $value ) {
			$ajax->setRequestHeader($name,$value);
		}
		
		//	Add custom headers
		$ajax->setRequestHeader("User-Agent","fixxPHP");
		
		if(!empty($options['data'])){
			$response=$ajax->send($options['data']);
		}else{
			$response=$ajax->send(null);
		}

		return $ajax;
	}
	
	public function head(){
		baseAPIClass::debug("head");
	}

	public function get($options){
		return $this->do_request("GET",$options);
	}

	public function post($options){
		return $this->do_request("POST",$options);
	}

	public function put($options){
		return $this->do_request("PUT",$options);
	}

	public function delete($options){
		return $this->do_request("DELETE",$options);
	}
}
?>